
source('utils.R')
source('read_dataset.R')

## inflation adjustment
cols = c('r_val','d_val','r_val_pcc_only','d_val_pcc_only')
df12[, (cols) := lapply(.SD, \(x) x * 1.12), .SDcols = cols]
df16[, (cols) := lapply(.SD, \(x) x * 1.037037), .SDcols = cols]

df12[,nat_quant_fine:=as.numeric(as.character(nat_quant_fine))]

df12[,nq_bin:=fcase(nat_quant_fine < .9, '[0,90)',
                    nat_quant_fine < .99, '[90,99)',
                    nat_quant_fine < .999, '[99,99.9)',
                    nat_quant_fine < 1.01, '[99.9,)',
                    default = NA_character_)]

df16[,nat_quant_fine:=as.numeric(as.character(nat_quant_fine))]

df16[,nq_bin:=fcase(nat_quant_fine < .9, '[0,90)',
                    nat_quant_fine < .99, '[90,99)',
                    nat_quant_fine < .999, '[99,99.9)',
                    nat_quant_fine < 1.01, '[99.9,)',
                    default = NA_character_)]

df20[,nat_quant_fine:=as.numeric(as.character(nat_quant_fine))]

df20[,nq_bin:=fcase(nat_quant_fine < .9, '[0,90)',
                    nat_quant_fine < .99, '[90,99)',
                    nat_quant_fine < .999, '[99,99.9)',
                    nat_quant_fine < 1.01, '[99.9,)',
                    default = NA_character_)]

bintot12 = df12[,.(r = sum(r_val,na.rm=T), d = sum(d_val,na.rm=T)),nq_bin][,cycle:=2012]
bintot16 = df16[,.(r = sum(r_val,na.rm=T), d = sum(d_val,na.rm=T)),nq_bin][,cycle:=2016]
bintot20 = df20[,.(r = sum(r_val,na.rm=T), d = sum(d_val,na.rm=T)),nq_bin][,cycle:=2020]

out = rbindlist(list(bintot12,bintot16,bintot20))

out = melt(out, c(1,4),variable.name = 'party')
out[,cycle_total:=sum(value),.(cycle,party)]

out[,pct_of_total_from_this_bin:=value/cycle_total]

out = out %>% group_by(nq_bin,cycle) %>% summarise(reliance_diff = value[party=='r']-value[party=='d'])

save(out, file = 'summary_data/fig4.rda')
